import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {routerRedux, Link} from 'dva/router';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message,
    Checkbox,
    Badge,
    Popconfirm,
    Divider,
    Table,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import defaultAvatar from '../../assets/admin_logo.png';
import styles from './Banner.less';
import EditTableCell from './EditTableCell';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['关闭', '运行中', '已上线', '异常'];

const CreateForm = Form.create()(props => {
    const {modalVisible, form, handleAdd, handleModalVisible} = props;
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            form.resetFields();
            handleAdd(fieldsValue);
        });
    };
    return (
        <Modal
            title="新建规则"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={() => handleModalVisible()}
        >
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="描述">
                {form.getFieldDecorator('desc', {
                    rules: [{required: true, message: 'Please input some description...'}],
                })(<Input placeholder="请输入"/>)}
            </FormItem>
        </Modal>
    );
});

const tabList = [
    {
        key: '0',
        tab: '横向分类',
    },
    {
        key: '1',
        tab: '纵向分组',
    },
];

const action = (
    <div>
        <Button type="primary"><Link to={`/index/group-save`}>新增</Link></Button>
    </div>
);


@connect(({indexGroup, loading}) => ({
    indexGroup,
    loading: loading.models.indexGroup,
}))
@Form.create()
export default class TableList extends PureComponent {
    state = {
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        addInputValue: '',
        checkedGroupList: [],
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'indexGroup/fetch',
        });
        /*dispatch({
         type : 'indexGroup/fetchGroup',
         });*/
    }

    bindDelete = (id)=> {
        this.props.dispatch({
            type: 'indexGroup/deleteItem',
            payload: {
                id: id
            }
        }).then(res=> {
            if (res) {
                message.success('删除成功');
            } else {
                message.error('删除失败');
            }
        })
    }

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            startIndex: (pagination.current - 1) * pagination.pageSize, //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'indexGroup/fetch',
            payload: params,
        });
    };
    onGroupChange = (checkedValues)=> {
        console.log(checkedValues);
        this.setState({
            checkedGroupList: checkedValues
        });
        //this.onGroupInfo.groupIds = checkedValues;
    }

    handleAddGroup = (e)=> {
        e.preventDefault();
        const {addInputValue} = this.state;
        const {dispatch}  = this.props;
        if (addInputValue == '') {
            return false;
        }
        dispatch({
            type: 'indexGroup/addGroup',
            payload: {
                name: addInputValue
            },
        }).then(()=> {
            this.setState({
                addInputValue: ''
            });
        })
    };
    handleGroup = ()=> {
        //const {userIds} = this.onGroupInfo;
        const {selectedRows, checkedGroupList} = this.state;
        if (checkedGroupList.length == 0) {
            //console.error('选中的分组用户为空');
            message.error('你还未选择分组');
            return;
        }
        //console.log(this.onGroupInfo);
        this.props.dispatch({
            type: 'indexGroup/goodsGroup',
            payload: {
                ids: selectedRows.map(row => row.id).join(','),
                groups: checkedGroupList.join(',')
            }
        }).then(()=> {
            //message.success('分组成功');
            this.setState({
                modalVisible: false,
                checkedGroupList: [],
            });
        });

    };
    handleSelectGroup = row=> {
        console.log('row', [row]);
        let groups = [];  //计算出当前已有分组ID值
        this.props.indexGroup.group.forEach(v=> {
            row.groups.forEach(s=> {
                if (v.name == s) {
                    groups.push(v.name);
                }
            })
        });

        this.setState({
            modalVisible: true,
            selectedRows: [row],
            checkedGroupList: groups,
        });
    };

    onCellChange = (key, dataIndex) => {
        return (value) => {
            console.log(value);
            if (isNaN(value)) {
                message.error('权重必须为0-100的数值');
                return false;
            } else if (Number(value) > 100 || Number(value) < 0) {
                message.error('权重必须为0-100的数值');
                return false;
            }
            this.props.dispatch({
                type: 'indexGroup/changeWeight',
                payload: {
                    id: key,
                    dataIndex,
                    value: Number(value),
                }
            });
        };
    };
    changeStatus = (item)=> {
        const {id, status} = item;
        console.log('item', item);
        this.props.dispatch({
            type: 'indexGroup/changeStatus',
            payload: {
                id,
                status: status ? 0 : 1
            }
        })
    };

    renderForm() {
        return this.renderSimpleForm();
    }

    handleTabChange = (key)=> {
        console.log(key);
        const {dispatch} = this.props;
        dispatch({
            type: 'indexGroup/fetch',
            payload: {
                type: key
            }
        });
    }

    render() {
        const {indexGroup: {data, group}, loading} = this.props;
        const {selectedRows, modalVisible, addInputValue, checkedGroupList} = this.state;

        //console.log(data);
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id'
            },
            {
                title: '标题',
                dataIndex: 'title'
            },
            {
                title: '描述',
                dataIndex: 'desc'
            },
            {
                title: '图片',
                dataIndex: 'img',
                render: val=> {
                    return <img src={val || defaultAvatar} width="60" height={60}/>
                }
            },
            {
                title: '类型',
                dataIndex: 'type',
                render: (val, record)=> {
                    let type = '';
                    if(record.type == 0){//0横向分类，1纵向分组
                        type =  '横向分类'
                    }else{
                        switch (record.display_style){
                            case 1:
                                type = '四宫格';
                                break;
                            case 2:
                                type = '一主三副';
                                break;
                            case 3:
                                type = '横向滑动';
                                break;
                            case 4:
                                type = '两排六个';
                                break;
                            case 5:
                                type = '一主两副';
                                break;
                            default:
                                type = '独占一行';
                        }
                    }
                    return type;
                }
            },
            {
                title: '权重',
                dataIndex: 'weight',
                render: (val, record) => {
                    return <EditTableCell
                        value={val || 0}
                        onChange={this.onCellChange(record.id, 'weight')}
                    />
                }
            },
            {
                title: '状态',
                dataIndex: 'status',
                render: (val) => {
                    return <Badge status={val ? 'success' : 'error'} text={val ? '已上架' : '已下架'}/>
                }
            },
            {
                title: '操作',
                render: (text, record) => (
                    <Fragment>
                        <Popconfirm title="你确定删除？" okText="确定" cancelText="取消" onConfirm={()=> {
                            this.bindDelete(record.id)
                        }}>
                            <a href="">删除</a>
                        </Popconfirm>
                        <Divider type="vertical"/>
                        <a href="javascript:;" onClick={ ()=> {
                            this.changeStatus(record)
                        } }>{record.status ? '下架' : '上架'}</a>
                        <Divider type="vertical"/>
                        <Link to={`/index/group-save?id=${record.id}`}>修改</Link>
                        <Divider type="vertical"/>
                        <Link to={`/index/group-goods?id=${record.id}`}>管理商品</Link>
                    </Fragment>
                ),
            },
        ];

        return (
            <PageHeaderLayout
                title="首页分组列表"
                tabList={tabList}
                action={action}
                onTabChange={ this.handleTabChange }
            >
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <Table columns={columns} dataSource={data} loading={loading} rowKey="id"/>
                    </div>
                </Card>
            </PageHeaderLayout>
        );
    }
}
